package com.tj.template.application.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.google.common.collect.Lists;
import com.tj.bo.account.client.AccountQueryService;
import com.tj.bo.account.client.CreateAccountService;
import com.tj.bo.account.client.DepositService;
import com.tj.bo.account.client.enums.AccountTypeEnum;
import com.tj.bo.account.client.vo.BalanceVO;
import com.tj.bo.account.client.vo.CreateAccountVO;
import com.tj.bo.common.conf.config.RedisConfigUtil;
import com.tj.bo.common.conf.constant.RedisKey;
import com.tj.bo.common.conf.enums.BonusStatusEnum;
import com.tj.bo.common.conf.enums.RestCodeEnum;
import com.tj.bo.common.conf.enums.UserActivityEnum;
import com.tj.bo.common.conf.util.MobileUtils;
import com.tj.bo.common.conf.util.SensitiveInfoUtils;
import com.tj.bo.user.client.*;
import com.tj.bo.user.client.enums.UserRealFlagEnum;
import com.tj.bo.user.client.enums.UserRegisterTypeEnum;
import com.tj.bo.user.client.enums.UserSocialTypeEnum;
import com.tj.bo.user.client.vo.input.*;
import com.tj.bo.user.client.vo.output.*;
import com.tj.template.application.user.input.UserPasswordLoginApInput;
import com.tj.template.application.user.input.UserPasswordResetApInput;
import com.tj.template.application.user.input.UserRegisterApInput;
import com.tj.template.application.user.input.UserSocialLoginApInput;
import com.tj.template.application.user.output.*;
import com.tj.template.config.vo.RequestBasicInfo;
import com.tj.template.config.vo.RequestLocalInfo;
import com.tj.template.config.vo.UserAccessInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * 提供设备登录、注册
 * User: binary
 * Date: 2020/6/9
 * Time: 下午4:53
 */
@Component
public class UserBaseApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserBaseApplication.class);

    @Autowired
    private RedisConfigUtil binaryConfigUtil;

    @Autowired
    private UserRegisterService userRegisterService;

    @Autowired
    private UserCheckService userCheckService;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private CreateAccountService createAccountService;

    @Autowired
    private UserPromotionService userPromotionService;

    @Autowired
    private AccountQueryService accountQueryService;

    @Autowired
    private UserActivityService userActivityService;
    @Autowired
    private DepositService depositService;

    /**
     * 用户初始化接口
     *
     * @return
     */
    public UserInitApOutput init() {
        RequestBasicInfo requestBasicInfo = RequestLocalInfo.getRequestBasicInfo();
        if (requestBasicInfo == null || StringUtils.isEmpty(requestBasicInfo.getDeviceId())) {
            throw new ApplicationException("Device ID is empty!");
        }
        if (StringUtils.isNotEmpty(requestBasicInfo.getRealToken())) {
            if (!userCheckService.checkByRealToken(requestBasicInfo.getRealToken())) {
                throw new ApplicationException(RestCodeEnum.TOKEN_NOT_AVAILABLE);
            }
            UserQueryOutput userQueryVo = userQueryService.getUserInfoByRealToken(requestBasicInfo.getRealToken());
            return new UserInitApOutput(userQueryVo.getUserBaseReal() != null ? userQueryVo.getUserBaseReal().getToken() : "",
                    userQueryVo.getUserBaseDemo() != null ? userQueryVo.getUserBaseDemo().getToken() : "");
        }

        //只有第一次打开APP才会为空
        if (userCheckService.isDeviceRegistered(requestBasicInfo.getAppCode(), requestBasicInfo.getDeviceId())) {
            UserQueryOutput userQueryOutput = userQueryService.getUserInfoByDeviceId(requestBasicInfo.getAppCode(), requestBasicInfo.getDeviceId());
            return new UserInitApOutput("", userQueryOutput.getUserBaseDemo().getToken());
        } else {
            UserRegisterInput userRegisterInput = new UserRegisterInput();
            userRegisterInput.setUserRegisterTypeEnum(UserRegisterTypeEnum.IMEI);
            userRegisterInput.setEmail("");
            userRegisterInput.setOpenId("");
            userRegisterInput.setDeviceId(requestBasicInfo.getDeviceId());
            userRegisterInput.setPassword("");
            userRegisterInput.setAppCode(requestBasicInfo.getAppCode());
            userRegisterInput.setPackageName(requestBasicInfo.getPackageName());
            userRegisterInput.setClientId(requestBasicInfo.getClientId());
            userRegisterInput.setPlatform(requestBasicInfo.getPlatform());
            userRegisterInput.setVersion(requestBasicInfo.getAppVersion());
            userRegisterInput.setVersionCode(requestBasicInfo.getVersionCode());
            userRegisterInput.setChannel(requestBasicInfo.getChannel());
            userRegisterInput.setIp(requestBasicInfo.getIp());

            UserRegisterOutput userRegisterVo = userRegisterService.deviceRegister(userRegisterInput);
            UserInitApOutput userInitResponse = new UserInitApOutput(userRegisterVo.getRealToken(), userRegisterVo.getDemoToken());
            userInitResponse.setDeviceDemoRegister(true);
            userInitResponse.setDemoUserCode(userRegisterVo.getDemoUserCode());
            return userInitResponse;
        }
    }

    /**
     * 注册
     *
     * @param userRegisterRequest
     * @return
     */
    public UserRegisterApOutput register(UserRegisterApInput userRegisterRequest) {
        //密码规则校验
        if (!passwordRuleChecking(userRegisterRequest.getPassword())) {
            throw new ApplicationException("The password must be longer than 8 digits and less then 32 digits");
        }
        RequestBasicInfo requestBasicInfo = RequestLocalInfo.getRequestBasicInfo();
        UserRegisterInput userRegisterInput = new UserRegisterInput();
        userRegisterInput.setUserRegisterTypeEnum(UserRegisterTypeEnum.EMAIL);
        userRegisterInput.setEmail(userRegisterRequest.getEmail());
        userRegisterInput.setOpenId("");
        userRegisterInput.setDeviceId(requestBasicInfo.getDeviceId());
        userRegisterInput.setPassword(userRegisterRequest.getPassword());
        userRegisterInput.setAppCode(requestBasicInfo.getAppCode());
        userRegisterInput.setPackageName(requestBasicInfo.getPackageName());
        userRegisterInput.setClientId(requestBasicInfo.getClientId());
        userRegisterInput.setPlatform(requestBasicInfo.getPlatform());
        userRegisterInput.setVersion(requestBasicInfo.getAppVersion());
        userRegisterInput.setVersionCode(requestBasicInfo.getVersionCode());
        userRegisterInput.setChannel(requestBasicInfo.getChannel());
        userRegisterInput.setIp(requestBasicInfo.getIp());

        if (userCheckService.isEmailRegistered(userRegisterInput.getAppCode(), userRegisterInput.getEmail())) {
            throw new ApplicationException("The email address has been registered!");
        }

        UserRegisterOutput userRegisterOutput = userRegisterService.emailRegister(userRegisterInput);
        UserRegisterApOutput userRegisterAppOutput = new UserRegisterApOutput();
        userRegisterAppOutput.setRealUserCode(userRegisterOutput.getRealUserCode());
        userRegisterAppOutput.setRealToken(userRegisterOutput.getRealToken());
        userRegisterAppOutput.setDemoUserCode(userRegisterOutput.getDemoUserCode());
        userRegisterAppOutput.setDemoToken(userRegisterOutput.getDemoToken());
        return userRegisterAppOutput;
    }

    /**
     * 营销注册
     * @param type
     * @param loginAccount
     * @param password
     * @param verifyCode
     * @return
     */
    public UserRegisterApOutput promotionRegister(Integer type, String loginAccount, String password, String verifyCode, String inviteCode){

        if (!passwordRuleChecking(password)) {
            throw new ApplicationException("The password must be longer than eight digits and contain numbers and letters");
        }

        RequestBasicInfo requestBasicInfo = RequestLocalInfo.getRequestBasicInfo();
        UserRegisterInput userRegisterInput = new UserRegisterInput();
        userRegisterInput.setUserRegisterTypeEnum(UserRegisterTypeEnum.getEnum(type));
        userRegisterInput.setOpenId("");
        userRegisterInput.setDeviceId(requestBasicInfo.getDeviceId());
        userRegisterInput.setPassword(password);
        userRegisterInput.setAppCode(requestBasicInfo.getAppCode());
        userRegisterInput.setPackageName(requestBasicInfo.getPackageName());
        userRegisterInput.setClientId(requestBasicInfo.getClientId());
        userRegisterInput.setPlatform(requestBasicInfo.getPlatform());
        userRegisterInput.setVersion(requestBasicInfo.getAppVersion());
        userRegisterInput.setVersionCode(requestBasicInfo.getVersionCode());
        userRegisterInput.setChannel(requestBasicInfo.getChannel());
        userRegisterInput.setIp(requestBasicInfo.getIp());
        userRegisterInput.setInviteCode(inviteCode);

        UserAccessInfoRO userAccessInfoRO = null;
        if(type == UserRegisterTypeEnum.EMAIL.getType()){
            userRegisterInput.setEmail(loginAccount);
            userAccessInfoRO = userCheckService.getUserAccessByEmail("BO", loginAccount);

        }else if(type == UserRegisterTypeEnum.MOBILE.getType()){
            userRegisterInput.setMobile(loginAccount);
            userAccessInfoRO = userCheckService.getUserAccessByMobile("BO", loginAccount);
        }

        if(userAccessInfoRO != null){
            UserRegisterApOutput userRegisterAppOutput = new UserRegisterApOutput();
            userRegisterAppOutput.setRealUserCode(userAccessInfoRO.getUserCode());
            userRegisterAppOutput.setRealToken(userAccessInfoRO.getToken());
            userRegisterAppOutput.setDemoUserCode("");
            userRegisterAppOutput.setDemoToken("");
            return userRegisterAppOutput;
        }else{
            UserRegisterOutput userRegisterOutput = userRegisterService.emailRegister(userRegisterInput);
            UserRegisterApOutput userRegisterAppOutput = new UserRegisterApOutput();
            userRegisterAppOutput.setRealUserCode(userRegisterOutput.getRealUserCode());
            userRegisterAppOutput.setRealToken(userRegisterOutput.getRealToken());
            userRegisterAppOutput.setDemoUserCode(userRegisterOutput.getDemoUserCode());
            userRegisterAppOutput.setDemoToken(userRegisterOutput.getDemoToken());

            CreateAccountVO createAccountVO = new CreateAccountVO();
            createAccountVO.setUserCode(userRegisterOutput.getRealUserCode());
            createAccountVO.setAccountTypeEnum(AccountTypeEnum.REAL);
            createAccountVO.setUserName("");
            createAccountVO.setMobile("");
            createAccountVO.setOperator("");
            createAccountService.createAccount(createAccountVO);

            CreateAccountVO createAccountVODemo = new CreateAccountVO();
            createAccountVODemo.setUserCode(userRegisterOutput.getDemoUserCode());
            createAccountVODemo.setAccountTypeEnum(AccountTypeEnum.DEMO);
            createAccountVODemo.setUserName("");
            createAccountVODemo.setMobile("");
            createAccountVODemo.setOperator("");
            createAccountService.createAccount(createAccountVODemo);
            return userRegisterAppOutput;
        }

    }

    /**
     * 注册协议
     *
     * @return
     */
    public RegisterProtocolApOutput getProtocol() {
        return new RegisterProtocolApOutput(binaryConfigUtil.getRegisterProtocol());
    }

    /**
     * 账号密码登录
     *
     * @param userPasswordLoginRequest
     * @return
     */
    public UserPasswordLoginApOutput passwordLogin(UserPasswordLoginApInput userPasswordLoginRequest) {

        RequestBasicInfo requestBasicInfo = RequestLocalInfo.getRequestBasicInfo();
        String appCode = requestBasicInfo.getAppCode();

        UserPasswordLoginInput userPasswordLoginInput = new UserPasswordLoginInput();
        userPasswordLoginInput.setLoginAccount(userPasswordLoginRequest.getEmail());
        userPasswordLoginInput.setAppCode(appCode);
        userPasswordLoginInput.setEmail(userPasswordLoginRequest.getEmail());
        userPasswordLoginInput.setPassword(userPasswordLoginRequest.getPassword());
        userPasswordLoginInput.setLoginType(userPasswordLoginRequest.getType());

        userPasswordLoginInput.setDeviceId(requestBasicInfo.getDeviceId());
        userPasswordLoginInput.setAppCode(requestBasicInfo.getAppCode());
        userPasswordLoginInput.setPackageName(requestBasicInfo.getPackageName());
        userPasswordLoginInput.setClientId(requestBasicInfo.getClientId());
        userPasswordLoginInput.setPlatform(requestBasicInfo.getPlatform());
        userPasswordLoginInput.setVersion(requestBasicInfo.getAppVersion());
        userPasswordLoginInput.setVersionCode(requestBasicInfo.getVersionCode());
        userPasswordLoginInput.setChannel(requestBasicInfo.getChannel());
        userPasswordLoginInput.setIp(requestBasicInfo.getIp());

        UserLoginOutput userLoginVo = userLoginService.passwordLogin(userPasswordLoginInput);
        return new UserPasswordLoginApOutput(userLoginVo.getRealToken());
    }

    /**
     * 社交登录
     *
     * @param userSocialLoginRequest
     * @return
     */
    public UserSocialLoginApOutput socialLogin(UserSocialLoginApInput userSocialLoginRequest) {
        UserSocialTypeEnum userSocialTypeEnum = UserSocialTypeEnum.getEnum(userSocialLoginRequest.getSocialType());
        if (userSocialTypeEnum == null) {
            throw new ApplicationException("socialType is invalid");
        }
        RequestBasicInfo requestBasicInfo = RequestLocalInfo.getRequestBasicInfo();
        String appCode = requestBasicInfo.getAppCode();
        UserRegisterTypeEnum userRegisterTypeEnum = UserRegisterTypeEnum.FACEBOOK;
        if (!Objects.equals(userSocialTypeEnum, UserSocialTypeEnum.FACEBOOK)) {
            userRegisterTypeEnum = UserRegisterTypeEnum.GOOGLE;
        }
        if (userCheckService.isSocialRegistered(appCode, userRegisterTypeEnum, userSocialLoginRequest.getOpenId())) {
            UserSocialLoginInput userSocialLoginInput = new UserSocialLoginInput();
            userSocialLoginInput.setUserRegisterTypeEnum(userRegisterTypeEnum);
            userSocialLoginInput.setOpenId(userSocialLoginRequest.getOpenId());
            userSocialLoginInput.setDeviceId(requestBasicInfo.getDeviceId());
            userSocialLoginInput.setAppCode(requestBasicInfo.getAppCode());
            userSocialLoginInput.setPackageName(requestBasicInfo.getPackageName());
            userSocialLoginInput.setClientId(requestBasicInfo.getClientId());
            userSocialLoginInput.setPlatform(requestBasicInfo.getPlatform());
            userSocialLoginInput.setVersion(requestBasicInfo.getAppVersion());
            userSocialLoginInput.setVersionCode(requestBasicInfo.getVersionCode());
            userSocialLoginInput.setChannel(requestBasicInfo.getChannel());
            userSocialLoginInput.setIp(requestBasicInfo.getIp());
            UserLoginOutput userLoginOutput = userLoginService.socialLogin(userSocialLoginInput);

            UserSocialLoginApOutput userSocialLoginResponse = new UserSocialLoginApOutput();
            userSocialLoginResponse.setRealUserCode("");
            userSocialLoginResponse.setRealToken(userLoginOutput.getRealToken());
            userSocialLoginResponse.setDemoUserCode("");
            userSocialLoginResponse.setDemoToken(userLoginOutput.getDemoToken());
            userSocialLoginResponse.setSocialRegister(false);
            return userSocialLoginResponse;
        } else {
            UserRegisterInput userRegisterInput = new UserRegisterInput();
            userRegisterInput.setUserRegisterTypeEnum(userRegisterTypeEnum);
            userRegisterInput.setEmail(userSocialLoginRequest.getEmail());//设置三方邮箱 只用来展示 不能用来登录
            userRegisterInput.setOpenId(userSocialLoginRequest.getOpenId());
            userRegisterInput.setDeviceId(requestBasicInfo.getDeviceId());
            userRegisterInput.setPassword("");
            userRegisterInput.setAppCode(requestBasicInfo.getAppCode());
            userRegisterInput.setPackageName(requestBasicInfo.getPackageName());
            userRegisterInput.setClientId(requestBasicInfo.getClientId());
            userRegisterInput.setPlatform(requestBasicInfo.getPlatform());
            userRegisterInput.setVersion(requestBasicInfo.getAppVersion());
            userRegisterInput.setVersionCode(requestBasicInfo.getVersionCode());
            userRegisterInput.setChannel(requestBasicInfo.getChannel());
            userRegisterInput.setIp(requestBasicInfo.getIp());
            userRegisterInput.setNickname(userSocialLoginRequest.getNickname());

            UserRegisterOutput userRegisterOutput = userRegisterService.openIdRegister(userRegisterInput);
            UserSocialLoginApOutput userSocialLoginResponse = new UserSocialLoginApOutput();
            userSocialLoginResponse.setRealUserCode(userRegisterOutput.getRealUserCode());
            userSocialLoginResponse.setRealToken(userRegisterOutput.getRealToken());
            userSocialLoginResponse.setDemoUserCode(userRegisterOutput.getDemoUserCode());
            userSocialLoginResponse.setDemoToken(userRegisterOutput.getDemoToken());
            userSocialLoginResponse.setSocialRegister(true);
            return userSocialLoginResponse;
        }
    }

    /**
     * 重置密码
     *
     * @param userPasswordResetRequest
     */
    public void passwordReset(UserPasswordResetApInput userPasswordResetRequest) {
        if (StringUtils.isEmpty(userPasswordResetRequest.getResetPasswordToken())
                || StringUtils.isEmpty(userPasswordResetRequest.getEmail())) {
            throw new ApplicationException("Link failure!");
        }
        if (StringUtils.isEmpty(userPasswordResetRequest.getNewPassword())) {
            throw new ApplicationException("Password can not be empty!");
        }
        //密码规则校验
        if (!passwordRuleChecking(userPasswordResetRequest.getNewPassword())) {
            throw new ApplicationException("The password must be longer than eight digits and contain numbers and letters");
        }
        String data = redisClient.get(RedisKey.PASSWORD_RESET_KEY, userPasswordResetRequest.getResetPasswordToken());
        if (StringUtils.isEmpty(data)) {
            throw new ApplicationException("Link failure!");
        }

        JSONObject dataObj = JSON.parseObject(data);
        String email = dataObj.getString("email");
        if (!userPasswordResetRequest.getEmail().equals(email)) {
            throw new ApplicationException("Link failure!");
        }
        String appCode = dataObj.getString("appCode");

        //重置密码
        UserResetPasswordInput userResetPasswordInput = new UserResetPasswordInput();
        userResetPasswordInput.setAppCode(appCode);
        userResetPasswordInput.setEmail(email);
        userResetPasswordInput.setPassword(userPasswordResetRequest.getNewPassword());
        userRegisterService.resetPassword(userResetPasswordInput);
        //缓存失效
        redisClient.del(RedisKey.PASSWORD_RESET_KEY, userPasswordResetRequest.getResetPasswordToken());
    }

    /**
     * 密码规则校验
     *
     * @param password
     * @return
     */
    private boolean passwordRuleChecking(String password) {
        //至少包含数字跟字母，可以有字符
//        Pattern pattern = Pattern.compile("(?=.*([a-zA-Z].*))(?=.*[0-9].*)[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,20}$");
//        boolean result = pattern.matcher(password).matches();
//        System.out.println(password + "," + result);
//        return result;
        if(StringUtils.isEmpty(password)){
            return false;
        }

        if(password.length()>32 || password.length()<6){
            return false;
        }

        return true;
    }

    /**
     * 获取我的页面 列表信息
     *
     * @return
     */
    public UserMyActionApOutput getUserMyInfo() {
        UserAccessInfo userAccessInfo = RequestLocalInfo.getCurrentUser();
        new UserMyActionApOutput();
        UserMyActionApOutput userMyActionApOutput = new UserMyActionApOutput();
        List<UserMyActionApOutput.ActionItem> actions = Lists.newArrayList();
        UserMyActionApOutput.ActionItem item = new UserMyActionApOutput.ActionItem("Balance", "https://scrm-hk.oss-cn-hongkong.aliyuncs.com/scrm/images/mipmap-xxhdpi/balance.png", "URL/balance", true);
        actions.add(item);
        item = new UserMyActionApOutput.ActionItem("Setting", "https://scrm-hk.oss-cn-hongkong.aliyuncs.com/scrm/images/mipmap-xxhdpi/setting.png", "URL/setting", false);
        actions.add(item);
        item = new UserMyActionApOutput.ActionItem("Contact Us", "https://scrm-hk.oss-cn-hongkong.aliyuncs.com/scrm/images/mipmap-xxhdpi/contact.png", "http://oss.loanshield.in/agreement/help.html", false);
        actions.add(item);
        item = new UserMyActionApOutput.ActionItem("Q&A", "https://scrm-hk.oss-cn-hongkong.aliyuncs.com/scrm/images/mipmap-xxhdpi/q%26a.png", "http://oss.loanshield.in/agreement/FAQS.html", false);
        actions.add(item);
        if (userAccessInfo.isVisitors()) {
            userMyActionApOutput.setActions(actions);
        } else {
            item = new UserMyActionApOutput.ActionItem("Exit", "https://scrm-hk.oss-cn-hongkong.aliyuncs.com/scrm/images/mipmap-xxhdpi/exit.png", "URL/logout", true);
            actions.add(item);
            UserQueryOutput userQueryVo = userQueryService.getUserInfoByRealToken(userAccessInfo.getUserBaseReal().getToken());
            BalanceVO realUserBalanceInfo = accountQueryService.getRealUserBalanceInfo(userQueryVo.getUserBaseReal().getUserCode());
            userMyActionApOutput = new UserMyActionApOutput(userQueryVo, realUserBalanceInfo.getRealBalance(), actions);
        }
        UserMyActionApOutput.InviteFriendMenuVO inviteFriendMenuVO = new UserMyActionApOutput.InviteFriendMenuVO("https://scrm-hk.oss-cn-hongkong.aliyuncs.com/scrm/images/invite_friend.png", "URL/inviteFriends", false);
        userMyActionApOutput.setInviteFriendMenu(inviteFriendMenuVO);
        String version = RequestLocalInfo.getRequestBasicInfo().getAppVersion();
        for (UserMyActionApOutput.ActionItem actionItem : userMyActionApOutput.getActions()) {
            if (actionItem.getTitle().equalsIgnoreCase("Contact Us")) {
                actionItem.setJumpUrl("http://oss.loanshield.in/agreement/help.html");
            }
        }

        return userMyActionApOutput;
    }

    /**
     * 邀请好友页面信息
     * @return
     */
    public UserPromotionInviteResponse getInviteBonus(){
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        UserPromotionInviteResponse response = new UserPromotionInviteResponse();
        UserAccessInfoRO userAccessInfoRO = userQueryService.getUserAccessInfoByUserCode(userCode);
        if(userAccessInfoRO.getRealFlag() != UserRealFlagEnum.REAL.getType()){
            response.setIntroduction(binaryConfigUtil.getIntroduction());
            response.setBonus(binaryConfigUtil.getInviteBonus().toString());
            response.setTotalBonus("PKR0");
            response.setInviteNum(0);
            response.setInvitationCode("");
            response.setInvitationUrl(null);
        }else{
            UserPromotionInfoRO userPromotionInfo = userPromotionService.getUserPromotionByUserCode(userCode);
            response.setIntroduction(binaryConfigUtil.getIntroduction());
            response.setBonus(binaryConfigUtil.getInviteBonus().toString());
            response.setTotalBonus(userPromotionInfo.getTotalBonus().toString());
            response.setInviteNum(userPromotionInfo.getTotalInvitePeople());
            response.setInvitationCode(userPromotionInfo.getInvitationCode());
            response.setInvitationUrl(binaryConfigUtil.getInviteUrl() + "?inviteCode=" + userPromotionInfo.getInvitationCode());
        }
        return response;
    }

    public UserPromotionRecordResponse getInviteRecord(){
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        List<UserPromotionInviteRecordRO> userPromotionInviteRecords = userPromotionService.getUserPromotionInviteRecordByUserCode(userCode);
        List<UserPromotionRecordResponse.InviteRecord> inviteRecords = Lists.newArrayList();
        Integer rewardedBonus = 0;
        Integer pendingBonus = 0;
        Integer rewardedUserNum = 0;
        Integer pendingUserNum = 0;
        if(CollectionUtils.isNotEmpty(userPromotionInviteRecords)){
            for(UserPromotionInviteRecordRO recordRO : userPromotionInviteRecords){
                UserPromotionRecordResponse.InviteRecord inviteRecord = new UserPromotionRecordResponse.InviteRecord();
                inviteRecord.setInvitedFriendName(SensitiveInfoUtils.account(recordRO.getInvitedName()));
                inviteRecord.setInvitedRegisterDate(DateUtil.getDate(recordRO.getInvitedRegisterDate(), "dd/MM/yyyy HH:mm:ss"));
                inviteRecord.setBonus("PKR" + recordRO.getBonus());
                inviteRecord.setStatus(BonusStatusEnum.getEnumByCode(recordRO.getStatus()).getName());
                inviteRecords.add(inviteRecord);
                if(recordRO.getStatus() == BonusStatusEnum.COMPLETED.getCode()){
                    rewardedUserNum = rewardedUserNum + 1;
                    rewardedBonus = rewardedBonus + Integer.valueOf(recordRO.getBonus());
                }else if(recordRO.getStatus() == BonusStatusEnum.PROCESSING.getCode()){
                    pendingUserNum =  pendingUserNum + 1;
                    pendingBonus = pendingBonus + binaryConfigUtil.getInviteBonus();
                }
            }
        }
        UserPromotionRecordResponse recordResponse = new UserPromotionRecordResponse();
        recordResponse.setRewardedBonus("PKR" + rewardedBonus);
        recordResponse.setPendingBonus(("PKR" + pendingBonus));
        recordResponse.setRewardedUserNum(rewardedUserNum);
        recordResponse.setPendingUserNum(pendingUserNum);
        recordResponse.setTotalUserNum(rewardedUserNum + pendingUserNum);
        recordResponse.setInviteRecords(inviteRecords);
        return recordResponse;
    }


    public UserActivityPopupVO popup(){

        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();

        List<UserActivity> userActivities = userActivityService.queryActivityByUserCode(userCode, UserActivityEnum.POPUP.getCode());
        if(CollectionUtils.isEmpty(userActivities)){
            return null;
        }
        boolean hasDepositRecord = depositService.hasDepositSuccessRecord(userCode);
        List<UserActivity> newUserActivities = Lists.newArrayList();
        for(UserActivity userActivity : userActivities){
            if(userActivity.getVisibility() == 1 && hasDepositRecord){
                continue;
            }
            newUserActivities.add(userActivity);
        }
        if(CollectionUtils.isEmpty(newUserActivities)){
            return null;
        }
        UserActivityPopupVO userActivityPopup = new UserActivityPopupVO();
        userActivityPopup.setPopupType(1);
        userActivityPopup.setPopupId(newUserActivities.get(0).getActivityId());
        userActivityPopup.setUrl(newUserActivities.get(0).getUrl());
        userActivityPopup.setButtonText(newUserActivities.get(0).getButtonText());
        userActivityPopup.setImgUrl(newUserActivities.get(0).getImgUrl());
        userActivityPopup.setButtonImgUrl(newUserActivities.get(0).getButtonImgUrl());
        return userActivityPopup;

    }

    public void readPopup(Long popupId){
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        userActivityService.readActivity(popupId, userCode);
    }

    public List<UserBannerVO> getBanners(){
        List<UserBannerVO> banners = JSONObject.parseArray(binaryConfigUtil.getBanners(), UserBannerVO.class);
        return banners;
    }

    public void saveUserInfo(String name, String mobile, String email){

        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        UserAuthenticationRO userAuthenticationRO = new UserAuthenticationRO();
        userAuthenticationRO.setUserCode(userCode);
        userAuthenticationRO.setUserName(name.trim());
        userAuthenticationRO.setMobile(MobileUtils.removeExcess(mobile));
        userAuthenticationRO.setEmail(email.replaceAll(" ", ""));
        userRegisterService.userAuthentication(userAuthenticationRO);
    }

    public UserAuthenticationInfo getUserAuthenticationInfo(){
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        UserAccessInfoRO userAccessInfo = userQueryService.getUserAccessInfoByUserCode(userCode);

        UserAuthenticationInfo userAuthenticationInfo = new UserAuthenticationInfo();
        userAuthenticationInfo.setName(userAccessInfo.getUserName());
        userAuthenticationInfo.setEmail(userAccessInfo.getEmail());
        userAuthenticationInfo.setMobile(userAccessInfo.getMobile());
        userAuthenticationInfo.setTips(binaryConfigUtil.getUserAuthPageTips());
        return userAuthenticationInfo;
    }
}
